

#include "SdlEngine.h"

using namespace Iride;

SdlEngine::SdlEngine(int inputWidth, int inputHeight )
: mWidth(inputWidth), mHeight(inputHeight), mpScreen(NULL), mpVideoBuf(NULL), mInitialiased(false), mCleanedUp(false)
{

}

bool SdlEngine::Init()
{
	if (mInitialiased == false)
	{
		if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
		{
			return false;
		}

		if( (mpScreen = SDL_SetVideoMode(mWidth, mHeight, 32, SDL_HWSURFACE | SDL_DOUBLEBUF)) == NULL )
		{
			return false;
		}

		    Uint32 rmask, gmask, bmask, amask;

		/* SDL interprets each pixel as a 32-bit number, so our masks must depend
		   on the endianness (byte order) of the machine */
		#if SDL_BYTEORDER == SDL_BIG_ENDIAN
			rmask = 0xff000000;
			gmask = 0x00ff0000;
			bmask = 0x0000ff00;
			amask = 0x000000ff;
		#else
			rmask = 0x000000ff;
			gmask = 0x0000ff00;
			bmask = 0x00ff0000;
			amask = 0xff000000;
		#endif

		SDL_Surface* videoBufTemp = SDL_CreateRGBSurface(SDL_SWSURFACE, mWidth, mHeight, 32, rmask, gmask, bmask, amask);

		mpVideoBuf = SDL_DisplayFormat(videoBufTemp);

		SDL_FreeSurface(videoBufTemp);

		mInitialiased = true;
	}

    return true;
}

void SdlEngine::Render()
{
	SDL_BlitSurface(mpVideoBuf, NULL, mpScreen, NULL);

    SDL_Flip(mpScreen);

//	SDL_Rect dstrect;
//	dstrect.x = 0;
//    dstrect.y = 0;
//    dstrect.w = mpScreen->w;
//    dstrect.h = mpScreen->h;
//    SDL_UpdateRects(mpScreen, 1, &dstrect);
}


void SdlEngine::Update()
{
	Uint32 black = SDL_MapRGB(mpVideoBuf->format, 0, 0, 0);	// TODO: remove
    SDL_FillRect(mpVideoBuf, NULL, black);					// TODO: remove
}

bool SdlEngine::GetInput()
{
    bool res = true;
    SDL_Event Event;

    while(SDL_PollEvent(&Event))
    {
        res &= HandleEvent(&Event);
    }

    return res;
}

void SdlEngine::DrawPixel(int x, int y, unsigned char r, unsigned char g, unsigned char b)
{
	y = -y + mHeight - 1;

    Uint32 color = SDL_MapRGB(mpVideoBuf->format, r, g, b);

    if ( SDL_MUSTLOCK(mpVideoBuf) )
    {
        if ( SDL_LockSurface(mpVideoBuf) < 0 )
        {
            return;
        }
    }

	Uint32 *bufp;

	bufp = (Uint32 *)mpVideoBuf->pixels + y*mpVideoBuf->pitch/4 + x;
	*bufp = color;

    if ( SDL_MUSTLOCK(mpVideoBuf) )
    {
        SDL_UnlockSurface(mpVideoBuf);
    }
}

int SdlEngine::GetWidth()
{
	return mWidth;
}

int SdlEngine::GetHeight()
{
	return mHeight;
}

void SdlEngine::Cleanup()
{
	if (mCleanedUp == false)
	{
		SDL_FreeSurface(mpVideoBuf);
		SDL_FreeSurface(mpScreen);
		SDL_Quit();

		mCleanedUp = true;
	}
}

bool SdlEngine::HandleEvent(SDL_Event* Event)
{
    bool res = true;
    if(Event->type == SDL_QUIT)
    {
        res = false;
    }
    return res;
}

